package com.juneng.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.UploadResult;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.Upload;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/*图片上传*/
public class CosApi {
	private static final String secretId="AKIDRyEIp4osSq38zhiOTIqDTTO1NbZUhZx6";
	private static final String secretKey="EOQEuSjmZ77sNeesrZ1GFTaQkpd8QqxB";
	// 1 初始化用户身份信息(secretId, secretKey)
    private static final COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
    // 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
    private static final ClientConfig clientConfig = new ClientConfig(new Region("ap-shanghai"));
    // 3 生成cos客户端
    private static final COSClient cosclient = new COSClient(cred, clientConfig);
    // bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
    //钱包
//    private static final String bucketName = "wallet-1302737475";
    private static final String bucketName = "yiqixiu-1302737475";
	/**
	 * 上传文件
	 * @param path
	 * @param keys
	 * @return
	 */
	public static String  upload(String path,String keys){
    	try {
    		
			File localFile =new File(path);
			// 指定要上传到 COS 上的路径
			String key = "/yiqixiu"+keys;
//			String key = "/formal"+keys;
			PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
			// 本地文件上传
			ExecutorService threadPool = Executors.newFixedThreadPool(32);
			// 传入一个threadpool, 若不传入线程池, 默认TransferManager中会生成一个单线程的线程池。
			TransferManager transferManager = new TransferManager(cosclient, threadPool);
			Upload upload = transferManager.upload(putObjectRequest);
			 // 等待传输结束（如果想同步的等待上传结束，则调用 waitForCompletion）
			UploadResult uploadResult = upload.waitForUploadResult();
//			GeneratePresignedUrlRequest req =
//			        new GeneratePresignedUrlRequest(bucketName, key, HttpMethodName.GET);
//			URL url = cosclient.generatePresignedUrl(req);
			transferManager.shutdownNow();
			return  "http://yiqixiu-1302737475.file.myqcloud.com"+key;
			
		} catch (CosServiceException e) {
			e.printStackTrace();
			return null;
		} catch (CosClientException e) {
			e.printStackTrace();
			return null;
		} catch (InterruptedException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 图片
	 * @param localFile
	 * @param keys
	 * @return
	 */
	public static String upload(File  localFile,String keys){
		try {
			// 生成一个下载链接
			// bucket的命名规则为{name}-{appid} ，此处填写的存储桶名称必须为此格式
	     /*   DiskFileItem fi = (DiskFileItem)path.getFileItem();
			File localFile = fi.getStoreLocation();*/
			if(!localFile.exists()){
				return null;
			}else{
			// 指定要上传到 COS 上的路径

			String key = "/yiqixiu"+keys;
//			String key = "/formal"+keys;
			PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
			// 本地文件上传
			ExecutorService threadPool = Executors.newFixedThreadPool(32);
			// 传入一个threadpool, 若不传入线程池, 默认TransferManager中会生成一个单线程的线程池。
			TransferManager transferManager = new TransferManager(cosclient, threadPool);
			Upload upload = transferManager.upload(putObjectRequest);
			 // 等待传输结束（如果想同步的等待上传结束，则调用 waitForCompletion）
			UploadResult uploadResult = upload.waitForUploadResult();
			transferManager.shutdownNow();
			String url="http://yiqixiu-1302737475.file.myqcloud.com"+key;
			return  url;
			}
		} catch (CosServiceException e) {
			e.printStackTrace();
			return null;
		} catch (CosClientException e) {
			e.printStackTrace();
			return null;
		} catch (InterruptedException e) {
			e.printStackTrace();
			return null;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 删除文件
	 * @param url
	 */
	public static void deleteFile(String url){
		try {
//			if(!url.equals("http://yiqixiu-1302737475.file.myqcloud.com/error.jpg")){
			URL urs=new URL(url);
			cosclient.deleteObject(bucketName, urs.getPath());
//			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}finally{
			cosclient.shutdown();
		}
	}
	/**
	 * MultipartFile 转 File
	 * @param file
	 * @throws Exception
	 */
	public static File multipartFileToFile(MultipartFile file) throws Exception {
		File toFile = null;
		if (file.equals("") || file.getSize() <= 0) {
			file = null;
		} else {
			InputStream ins = null;
			ins = file.getInputStream();
			toFile = new File(file.getOriginalFilename());
			inputStreamToFile(ins, toFile);
			ins.close();
		}
		return toFile;
	}

	/**
	 * 获取流文件
	 * @param ins
	 * @param file
	 */
	private static void inputStreamToFile(InputStream ins, File file) {
		try {
			OutputStream os = new FileOutputStream(file);
			int bytesRead = 0;
			byte[] buffer = new byte[8192];
			while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
				os.write(buffer, 0, bytesRead);
			}
			os.close();
			ins.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
	/*	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm");
		Date date = new Date();
		String format = sdf.format(date);
		System.out.println(upload(file,format+".png"));*/
		System.out.println(upload("D:\\yiqixiu资料\\test227.png", "test227.png"));
	}

	
}
